<template>
  <a-card :bordered="false">
    <div>
      <a-tabs v-model="activeKey" @change="handleChangeTab">
        <a-tab-pane key="dust" tab="喷粉">

          <a-form layout="inline">
            <a-row :gutter="12">
              <a-col span="16">
                <a-form-item label="时间粒度">
                  <date-range-radio
                    key="energy"
                    :mode="dustMode"
                    :time.sync="time"
                    :type.sync="queryParam.timetype"
                    @changeData="searchData"
                    @clearValue="clearValue"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
          <a-card :bordered="false">
            <div id="echart" style="height: 400px; width: 100%"></div>
          </a-card>
        </a-tab-pane>
        <a-tab-pane key="elect" tab="电">
          <a-card :bordered="false" style="margin-bottom:12px">
            <a-form layout="inline">
              <a-row :gutter="12">
                <a-col span="16">
                  <a-form-item label="时间粒度">
                    <date-range-radio
                      key="energy"
                      :mode="electMode"
                      :time.sync="electTime"
                      :type.sync="queryParam.electTimetype"
                      @changeData="searchData"
                      @clearValue="clearValue"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-card>
          <a-card :bordered="false">
            <div id="electChart" style="height: 400px; width: 100%"></div>
          </a-card>
        </a-tab-pane>
        <a-tab-pane key="keli" tab="单耗">
          <a-card :bordered="false" style="margin-bottom:12px">
            <a-form layout="inline">
              <a-row :gutter="12">
                <a-col span="16">
                  <a-form-item label="时间粒度">
                    <date-range-radio
                      key="energy"
                      :mode="electMode"
                      :time.sync="keliTime"
                      :type.sync="queryParam.electTimetype"
                      @changeData="searchData"
                      @clearValue="clearValue"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-card>
          <a-card :bordered="false">
            <div id="keliChart" style="height: 400px; width: 100%"></div>
          </a-card>
        </a-tab-pane>
        <a-tab-pane key="heat" tab="蒸汽">
          <a-card :bordered="false" style="margin-bottom:12px">
            <a-form layout="inline">
              <a-row :gutter="12">
                <a-col span="16">
                  <a-form-item label="时间粒度">
                    <date-range-radio
                      key="energy"
                      :mode="electMode"
                      :time.sync="heatTime"
                      :type.sync="queryParam.electTimetype"
                      @changeData="searchData"
                      @clearValue="clearValue"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-card>
          <a-card :bordered="false">
            <div id="heatChart" style="height: 400px; width: 100%"></div>
          </a-card>
        </a-tab-pane>
        <a-tab-pane key="report" tab="报表统计">
          <a-card :bordered="false" style="margin-bottom:12px">
            <a-form layout="inline">
              <a-row :gutter="12">
                <a-col span="16">
                  <a-form-item label="时间粒度">
                    <date-range-radio
                      key="report"
                      :mode="dustMode"
                      :time.sync="reportTime"
                      :type.sync="queryParam.timetype"
                      @changeData="searchData"
                      @clearValue="clearValue"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-card>
          <a-table :columns="reportColumns" :data-source="reportDatas" :rowKey="(record) => `${record.workshop}-${record.team}`" bordered :scroll="{ x: scrollX }" size="middle" :pagination="false">
            <template slot="name" slot-scope="text">
              <a>{{ text }}</a>
            </template>
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </div>
  </a-card>
</template>

<script>
import moment from 'moment/moment'
import DateRangeRadio from '@comp/DateRangeRadio/DateRangeRadio'
import * as echarts from 'echarts'
import { getAction } from '@api/manage'
import ActHistoricDetailBtn from '@views/flowable/components/ActHistoricDetailBtn.vue'

export default {
  name: 'EnergyStatistics',
  components: {
    ActHistoricDetailBtn,
    DateRangeRadio
  },
  data() {
    return {
      activeKey: 'dust',
      dustMode: 'month',
      electMode: 'year',
      time: moment(new Date(), 'YYYY-MM'),
      reportTime: moment(new Date(), 'YYYY-MM'),
      electTime: moment(new Date(), 'YYYY'),
      keliTime: moment(new Date(), 'YYYY'),
      heatTime: moment(new Date(), 'YYYY'),
      queryParam: {
        // eneTypeId: '1787737587542962177',
        // unitPartId: '1788431068226838529',
        timetype: 'month',
        time: moment().format('YYYY-MM'),
        electTimetype: 'year',
        electTime: moment(new Date(), 'YYYY'),
      },
      columns: [],
      datas: [],
      reportColumns: [
        { title: '车间', dataIndex: 'workshop', key: 'workshop', width: 100,
          customRender: (text, row, index) => {
            const obj = {
              children: text,
              attrs: {},
            };

            // 获取当前车间名称的所有行
            const sameWorkshopRows = this.reportDatas.filter(item => item.workshop === row.workshop);

            // 如果是当前车间的第一行
            if (this.reportDatas.findIndex(item => item.workshop === row.workshop) === index) {
              obj.attrs.rowSpan = sameWorkshopRows.length;
            } else {
              // 其他行不显示
              obj.attrs.rowSpan = 0;
            }

            return obj;
          }
        },
        { title: '班组', dataIndex: 'team', key: 'team', width: 80 },
        { title: '电量', dataIndex: 'elect', key: 'elect', width: 100 },
        { title: '颗粒度', dataIndex: 'keli', key: 'keli', width: 100 },
        { title: '蒸汽', dataIndex: 'heat', key: 'heat', width: 100 }
      ],
      reportDatas: [],
    }
  },
  mounted() {
    this.searchData()
  },
  methods: {
    handleChangeTab() {
      this.$nextTick(() => {
        this.searchData();
      });
    },
    moment,
    clearValue() {
      this.$set(this.queryParam, 'time', null)
    },
    searchData() {
      // 设置时间格式
      if (this.activeKey === 'dust') {
        this.queryParam.time = moment(this.time).format('YYYY-MM')
        this.getChartData()
      } else if (this.activeKey === 'elect') {
        this.queryParam.electTime = moment(this.electTime).format('YYYY')
        this.getElectChartData()
      }else if (this.activeKey === 'keli') {
        this.queryParam.time = moment(this.keliTime).format('YYYY')
        this.getKeliChartData()
      }else if (this.activeKey === 'heat') {
        this.queryParam.time = moment(this.heatTime).format('YYYY')
        this.getHeatChartData()
      }else if (this.activeKey === 'report') {
        this.queryParam.reportTime = moment(this.reportTime).format('YYYY-MM')
        this.getReportTableData()
      }
    },
    getReportTableData() {
      getAction('/compute/eneRuleDataUnitpart/report', this.queryParam).then(res => {
        // 初始化数据数组
        this.reportDatas = this.processReportData(res.result);
      }).catch(error => {
        console.error('接口请求失败:', error);
        // 清空数据报表
        this.columns = [];
        this.datas = [];
      });
    },
    processReportData(data) {
      data.sort((a, b) => a.workshop.localeCompare(b.workshop));
      const result = [];
      const workshopNames = [...new Set(data.map(item => item.workshop))];
      const teamNames = [...new Set(data.map(item => item.team))];

      workshopNames.forEach(workshop => {
        teamNames.forEach(team => {
          const item = data.find(i => i.workshop === workshop && i.team === team);
          result.push({
            workshop,
            team,
            elect: item?.elect || 0,
            keli: item?.keli || 0,
            heat: item?.heat || 0
          });
        });
      });

      return result;
    },
    getChartData() {
      getAction('/compute/eneRuleDataUnitpart/DustDetail', this.queryParam)
        .then(res => {
          this.initChart(res.result)
        })
        .catch(error => {
          console.error('请求发生错误:', error)
          this.showErrorChart()
        })
    },

    getElectChartData() {
      getAction('/compute/eneRuleDataUnitpart/electDetail', this.queryParam)
        .then(res => {
          console.log(res.result)
          this.initElectChart(res.result)
        })
        .catch(error => {
          console.error('请求发生错误:', error)
          this.showErrorChart()
        })
    },
    getKeliChartData() {
      getAction('/compute/eneRuleDataUnitpart/keliDetail', this.queryParam)
        .then(res => {
          console.log(res.result)
          this.initKeliChart(res.result)
        })
        .catch(error => {
          console.error('请求发生错误:', error)
          this.showErrorChart()
        })
    },
    getHeatChartData() {
      getAction('/compute/eneRuleDataUnitpart/heatDetail', this.queryParam)
        .then(res => {
          console.log(res.result)
          this.initHeatChart(res.result)
        })
        .catch(error => {
          console.error('请求发生错误:', error)
          this.showErrorChart()
        })
    },


    initChart(result) {
      const chartDom = document.getElementById('echart')
      const myChart = echarts.init(chartDom)
     /* const times =result.total.allDate.map(t => t.computeTime)*/
      const times = [
        ...new Set([ // 使用Set去重
          ...(result.total['一车间']?.map(t => t.computeTime) || []),
          ...(result.total['二车间']?.map(t => t.computeTime) || []),
          ...(result.total['三车间']?.map(t => t.computeTime) || [])
        ])
      ];
      console.log("aaaaa",result.total['一车间']?.map(t => t.computeTime) || [],times)
      const option = {
        title: {
          text: '能源消耗趋势',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function (params) {
            let result = params[0].axisValue + '<br/>'; // 显示当前时间（x轴值）
            params.forEach(function (item) {
              // 获取当前数据项的完整数据（包括 rate、data、keli）
              const dataItem = item.data;
              result +=
                item.marker + ' ' + item.seriesName +
                ': 能耗率 ' + item.value +
                ', 生物颗粒 ' + (dataItem.keli || '0') +
                ', 喷粉量 ' + (dataItem.data || '0') + '<br/>';
            });
            return result;
          }
        },
/*        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },*/
        legend: {
          data: ['一车间','二车间','三车间'],
          type: 'plain', // 图例类型（plain普通/scroll可滚动）
          orient: 'horizontal', // 方向（horizontal水平/vertical垂直）
          bottom: 0
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: times
        },
        yAxis: {
          type: 'value',
          name: '能源消耗'
        },
        series: [
          {
            name: '一车间',
            type: 'line',
            data: (result.total["一车间"] || []).map(item => ({
              value: item.rate,    // 主值，对应能耗率（会默认显示在tooltip中）
              data: item.data,     // 产量数据
              keli: item.total     // 喷粉量数据（你代码中用的是total字段）
            })),
            lineStyle: {
              width: 3,
              color: '#1890ff'
            },
            connectNulls: true,
            symbolSize: 8,
            itemStyle: {
              color: '#1890ff'
            }
          },
          {
            name: '二车间',
            type: 'line',
            data: (result.total["二车间"] || []).map(item => ({
              value: item.rate,    // 主值，对应能耗率（会默认显示在tooltip中）
              data: item.data,     // 产量数据
              keli: item.total     // 喷粉量数据（你代码中用的是total字段）
            })),
            connectNulls: true,
            lineStyle: {
              width: 3,
              color: '#00ff00'
            },
            symbolSize: 8,
            itemStyle: {
              color: '#00ff00'
            }
          },
          {
            name: '三车间',
            type: 'line',
            data: (result.total["三车间"] || []).map(item => ({
              value: item.rate,    // 主值，对应能耗率（会默认显示在tooltip中）
              data: item.data,     // 产量数据
              keli: item.total     // 喷粉量数据（你代码中用的是total字段）
            })),
            connectNulls: true,
            lineStyle: {
              width: 3,
              color: '#8d31d4'
            },
            symbolSize: 8,
            itemStyle: {
              color: '#8d31d4'
            }
          }
        ]
      }

      myChart.setOption(option)
      window.addEventListener('resize', function() {
        myChart.resize()
      })
    },
    initElectChart(result) {
      const chartDom = document.getElementById('electChart');

      let myChart = echarts.getInstanceByDom(chartDom); // 获取已有实例

      // 如果已有实例，先销毁
      if (myChart) {
        myChart.dispose();
      }

      myChart = echarts.init(chartDom);

      if (!result || !result.months || !result.series || result.months.length === 0 || result.series.length === 0) {
        // 清空图表
        myChart.setOption({
          title: {
            text: '电能耗趋势(度/吨)',
            left: 'center'
          },
          xAxis: {},
          yAxis: {
            name: '度/吨'
          },
          series: [],
          graphic: {
            type: 'text',
            left: 'center',
            top: 'middle',
            silent: true,
            style: {
              fontWeight: 'bold',
              text: '暂无数据',
              fontSize: '100px'
            }
          },
        });
        return; // 直接返回，不继续执行后面的代码
      }

      // 提取月份数据
      const months = result.months;

      // 提取车间数据
      const workshops = result.series;

      // 构建图例数据
      const legendData = workshops.map(workshop => workshop.name);

      // 预定义颜色数组
      const colorPalette = [
        '#1890ff', '#00ff00', '#8d31d4', '#ffcc00',
        '#ff6b6b', '#4ecdc4', '#ff9f43', '#a55eea',
        '#2ecc71', '#e74c3c', '#3498db', '#f39c12'
      ];

      // 构建series数据 - 修改为显示rate值
      const series = workshops.map((workshop, index) => ({
        name: workshop.name,
        type: 'line',
        data: workshop.data.map((value, i) => ({
          value: workshop.rate[i], // 使用rate值作为主要数据
          electricity: value, // 保留用电量数据供tooltip使用
          output: workshop.outputData[i],
          rate: workshop.rate[i]
        })),
        lineStyle: {
          width: 3,
          color: colorPalette[index % colorPalette.length]
        },
        connectNulls: true,
        symbolSize: 8,
        itemStyle: {
          color: colorPalette[index % colorPalette.length]
        }
      }));

      const option = {
        title: {
          text: '电能耗趋势(度/吨)',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function (params) {
            let result = params[0].axisValue + '<br/>';
            params.forEach(function (item) {
              result += item.marker + ' ' + item.seriesName + ': ' +
                '用电量: ' + item.data.electricity + '（度）' + ' ，' +
                '产量: ' + item.data.output + '（吨）' + ' ，' +
                '能耗率: ' + item.data.rate + '（度/吨）' + '<br/>';
            });
            return result;
          }
        },
        legend: {
          data: legendData,
          type: 'plain',
          orient: 'horizontal',
          bottom: 0,
          textStyle: {
            // 如果需要，可以在这里指定图例文字样式
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: months,
          axisLabel: {
            formatter: function (value) {
              return value + '月'; // 在每个月份后面添加"月"字
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '度/吨'
        },
        series: series,
        color: colorPalette
      };

      myChart.setOption(option);
      window.addEventListener('resize', function() {
        myChart.resize();
      });
    },
    initKeliChart(result) {
      const chartDom = document.getElementById('keliChart');
      const myChart = echarts.init(chartDom);

      // 提取月份数据
      const months = result.month;

      // 提取车间数据
      const workshops = result.series;

      // 构建图例数据
      const legendData = workshops.map(workshop => workshop.name);

      // 预定义颜色数组
      const colorPalette = ['#1890ff', '#00ff00', '#8d31d4', '#ffcc00', '#ff6b6b', '#4ecdc4', '#ff9f43', '#a55eea'];

      // 构建series数据
      const series = workshops.map((workshop, index) => ({
        name: workshop.name,
        type: 'line',
        data: workshop.rate.map((value, index) => ({
          value: value,
          keli:workshop.total[index],
          data: workshop.data[index],
        })),
        lineStyle: {
          width: 3,
          color: colorPalette[index % colorPalette.length] // 使用预定义颜色
        },
        connectNulls: true,
        symbolSize: 8,
        itemStyle: {
          color: colorPalette[index % colorPalette.length] // 使用预定义颜色
        }
      }));

      const option = {
        title: {
          text: '单耗',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function (params) {
            let result = params[0].axisValue + '<br/>';
            params.forEach(function (item) {
              result += item.marker + ' ' + item.seriesName + 'rate: ' + item.value + ' (生物颗粒: ' + item.data.keli +'（kg）'+ ' 产量: '+item.data.data+'（吨）'+ ')<br/>';
            });
            return result;
          }
        },
        legend: {
          data: legendData,
          type: 'plain',
          orient: 'horizontal',
          bottom: 0,
          textStyle: {
            // 如果需要，可以在这里指定图例文字样式
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: months
        },
        yAxis: {
          type: 'value',
          name: 'kg/吨'
        },
        series: series,
        // 可选：如果你想确保图例使用相同的颜色，可以添加 color 配置
        color: colorPalette
      };

      myChart.setOption(option);
      window.addEventListener('resize', function() {
        myChart.resize();
      });
    },
    initHeatChart(result) {
      const chartDom = document.getElementById('heatChart');
      const myChart = echarts.init(chartDom);

      // 提取月份数据
      const months = result.month;

      // 提取车间数据
      const workshops = result.series;

      // 构建图例数据
      const legendData = workshops.map(workshop => workshop.name);

      // 预定义颜色数组
      const colorPalette = ['#1890ff', '#00ff00', '#8d31d4', '#ffcc00', '#ff6b6b', '#4ecdc4', '#ff9f43', '#a55eea'];

      // 构建series数据
      const series = workshops.map((workshop, index) => ({
        name: workshop.name,
        type: 'line',
        data: workshop.rate.map((value, index) => ({
          value: value,
          heat:workshop.total[index],
          data: workshop.data[index]
        })),
        lineStyle: {
          width: 3,
          color: colorPalette[index % colorPalette.length] // 使用预定义颜色
        },
        connectNulls: true,
        symbolSize: 8,
        itemStyle: {
          color: colorPalette[index % colorPalette.length] // 使用预定义颜色
        }
      }));

      const option = {
        title: {
          text: '蒸汽',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function (params) {
            let result = params[0].axisValue + '<br/>';
            params.forEach(function (item) {
              result += item.marker + ' ' + item.seriesName + 'rate: ' + item.value + ' (蒸汽: ' + item.data.heat +'（元）'+ ' 产量: '+item.data.data+'（吨）'+ ')<br/>';
            });
            return result;
          }
        },
        legend: {
          data: legendData,
          type: 'plain',
          orient: 'horizontal',
          bottom: 0,
          textStyle: {
            // 如果需要，可以在这里指定图例文字样式
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: months
        },
        yAxis: {
          type: 'value',
          name: '元/吨'
        },
        series: series,
        // 可选：如果你想确保图例使用相同的颜色，可以添加 color 配置
        color: colorPalette
      };

      myChart.setOption(option);
      window.addEventListener('resize', function() {
        myChart.resize();
      });
    },
    showErrorChart() {
      const chartDom = document.getElementById('echart')
      const myChart = echarts.init(chartDom)
      const option = {
        graphic: {
          type: 'text',
          left: 'center',
          top: 'middle',
          style: {
            text: '数据加载失败',
            fontSize: 16,
            fontWeight: 'bold'
          }
        }
      }
      myChart.setOption(option)
    },
    getTableData() {
      getAction('/compute/eneRuleDataUnitpart/DustDetail', this.queryParam)
        .then(res => {
          this.generateTableColumns(res.result)
        })
        .catch(error => {
          console.error('接口请求失败:', error)
          this.columns = []
          this.datas = []
        })
    },
    generateTableColumns(result) {
      const times = result.statis.map(t => t.computeTime)
      const types = new Set(result.statis.map(t => t.eneTypeId))

      // 生成数据
      this.datas = []
      types.forEach(type => {
        const temp = result.statis.filter(t => t.eneTypeId === type)
        const energyName = result.types.find(t => t.id === type)?.type || ''
        const row = { energyName, total: 0 }

        let totalAdd = 0
        temp.forEach(t => {
          row[t.computeTime] = t?.total ?? 0
          totalAdd += Number.parseFloat(t?.total ?? 0)
        })

        row.total = totalAdd.toFixed(2)
        this.datas.push(row)
      })

      // 生成列
      this.columns = [
        {
          title: '用能类型',
          dataIndex: 'energyName',
          fixed: 'left',
          width: 150
        },
        {
          title: '总计',
          dataIndex: 'total',
          fixed: 'left',
          width: 100
        }
      ]

      times.forEach((time, index) => {
        this.columns.push({
          title: time.split('-').pop(),
          dataIndex: time,
          width: index === times.length - 1 && times.length <= 10 ? undefined : 100
        })
      })
    }
  },
  computed: {
    scrollX() {
      return this.columns.reduce((preVal, curVal) => preVal + (curVal.width || 100), 0)
    }
  }
}
</script>

<style scoped>
.ant-table-bordered .ant-table-fixed-right table {
  border-left: none;
}
</style>